ServerEvents.loaded(event => {
    if (!event.server.persistentData.sleepless) {
        event.server.persistentData.sleepless = {}
    }
});

PlayerEvents.tick(event => {
    const player = event.player
    const gameTime = player.level.getTime()
    const uuid = player.getUuid()
    const player_data = event.server.persistentData.sleepless
    if (!player_data[uuid]){
        player_data[uuid] = {
            last_sleep: gameTime,
            // sleep_state: false
        }
    }

    const MODID = 'minecraft:'
    const debuff = [
        `${MODID}slowness`, //缓慢
        `${MODID}mining_fatigue`, //挖掘疲劳
        `${MODID}nausea`, //反胃
        `${MODID}blindness`, //失明
        `${MODID}hunger`, //饥饿
        `${MODID}weakness`, //虚弱
        `${MODID}poison`, //中毒
        `${MODID}wither`, //凋零
        `${MODID}levitation`, //漂浮
        `${MODID}unluck`, //霉运
        `${MODID}bad_omen`, //不祥征兆
        `${MODID}darkness` //黑暗
    ]
    // 检测睡觉状态并清除debuff
    const isSleep = player.isSleeping()
    if (isSleep) {
        player_data[uuid].last_sleep = gameTime
        debuff.forEach(effect => {
            if (player.hasEffect(effect)) {
                player.removeEffect(effect)
            }
        })
    }
    // player_data[uuid].sleep_state = true

    // 计算未休息时间
    const time_awake = gameTime - player_data[uuid].last_sleep
    const days = Math.floor(time_awake / 240)/100

    // 处罚
    if (days >= 3) player.potionEffects.add(`${MODID}weakness`, 500, 0)
    if (days >= 4) player.potionEffects.add(`${MODID}nausea`, 500, 1)
    if (days >= 5) player.potionEffects.add(`${MODID}mining_fatigue`, 500, 0)
    if (days >= 6) player.potionEffects.add(`${MODID}blindness`, 500, 1)
    if (days >= 7) {
        player_data[uuid].last_sleep = gameTime
        player.kill()
    }

    // 发送数据到client
    player.sendData('weak_sleep', { time_awake: time_awake, days: days})
})